package com.meisupic.copyright.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meisupic.copyright.domain.bo.SysUser;
import com.meisupic.copyright.domain.po.BusinessCooperationInfo;
import com.meisupic.copyright.domain.po.Users;
import com.meisupic.copyright.domain.po.VipOrder;
import com.meisupic.copyright.domain.vo.AccountInfoVo;
import com.meisupic.copyright.domain.vo.RealNameAuthVo;
import com.meisupic.copyright.domain.vo.ScanPayResultVO;
import com.meisupic.copyright.domain.vo.VipOrderVo;
import com.meisupic.copyright.repo.UsersRepo;
import com.meisupic.copyright.service.IAccountService;
import com.meisupic.copyright.service.ISalesService;
import com.meisupic.copyright.support.EhcacheHelper;
import com.meisupic.copyright.support.Message;
import com.meisupic.copyright.support.security.CustomPasswordEncode;
import com.meisupic.copyright.util.BeanMapper;
import com.meisupic.copyright.util.StringUtil;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author lanjian
 * @Date 2018/3/11 下午3:22
 */
@RestController
@RequestMapping("/account")
public class AccountInfoController extends BaseController {

  @Autowired
  private IAccountService accountService;

  @Autowired
  private ISalesService salesService;

  @Autowired
  private UsersRepo usersRepo;


  /**
   * 获取账户信息
   */
  @GetMapping("/getBaseInfo")
  public Message<AccountInfoVo> getAccountInfo() {
    Long userId = getUserId();
    AccountInfoVo accountInfoVo = accountService.getAccountInfo(userId);
    return Message.success(accountInfoVo);
  }

  /**
   * 更新账户信息
   */
  @PostMapping("/updateBaseInfo")
  public Message updateAccountInfo(AccountInfoVo accountInfoVo) {
    Long userId = getUserId();
    accountService.updateAccountInfo(accountInfoVo, userId);
    return Message.success(null);
  }

  @PostMapping("/updatePassword")
  public Message updatePassword(String password, String newPassword) {
    accountService.updatePassword(getUserId(), password, newPassword);
    return Message.success(null);
  }

  @GetMapping("/getRealNameAuthInfo")
  public Message<RealNameAuthVo> getRealNameAuthInfo() {
    Long userId = getUserId();
    RealNameAuthVo realNameAuthVo = accountService.getRealNameAuthInfo(userId);
    String documentNo = realNameAuthVo.getDocumetNo();

    documentNo = StringUtils.left(documentNo, 6).concat(StringUtils.removeStart(
        StringUtils.leftPad(StringUtils.right(documentNo, 4), StringUtils.length(documentNo), "*"),
        "***"));
    realNameAuthVo.setDocumetNo(documentNo);
    return Message.success(realNameAuthVo);
  }

  /**
   * 判断用户是否是VIP
   */
  @GetMapping("isVip")
  public Boolean addVipOrder() {
    Authentication authentication = SecurityContextHolder.getContext()
        .getAuthentication();
    if ("anonymousUser".equals(authentication.getPrincipal())) {
      try {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return accountService.isVip(getUserId());
  }

  @GetMapping("queryVipOrder")
  public VipOrderVo queryVipOrder() {
    Authentication authentication = SecurityContextHolder.getContext()
        .getAuthentication();
    if ("anonymousUser".equals(authentication.getPrincipal())) {
      try {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    VipOrder vipOrder = accountService.queryToPayVipOrder(getUserId());
    if (StringUtil.isEmpty(vipOrder)) {
      SysUser user = getUser();
      vipOrder = new VipOrder();
      vipOrder.setUserId(user.getId());
      vipOrder.setPayStatus(false);
      vipOrder.setUserName(user.getUsername());
      vipOrder = accountService.addVipOrder(vipOrder);
    }
    VipOrderVo vipOrderVo = BeanMapper.map(vipOrder, VipOrderVo.class);
    return vipOrderVo;
  }

  @PostMapping("getWeiXinPayQrcode")
  public ScanPayResultVO getWeiXinPayQrcode(String orderNo) {
    return accountService.getWeixinPayQrcode(orderNo);
  }

  @GetMapping("getPayStatus")
  public boolean getPayStatus(String orderNo) {
    if (StringUtil.isEmpty(orderNo)) {
      return false;
    }
    VipOrder vipOrder = accountService.findVipOrderByOrderNo(orderNo);
    if (StringUtil.isEmpty(vipOrder)) {
      return false;
    }
    return vipOrder.getPayStatus();
  }


  @GetMapping("/sendValidateSms")
  public Message getSmsVerifyCode(String mobile, String ctoken) {
    List<Users> users = usersRepo.findByUserNameIs(mobile);
    String smsContent;
    if (!StringUtil.isEmpty(users)) {
      return Message.error("手机号已注册");
    } else {
      int randomCode = StringUtil.getRangeRandomCode(100000, 999999);
      EhcacheHelper.put("randomCodeCache", ctoken, randomCode);
      smsContent = "【美素版权】注册验证码" + randomCode;
      String sendResult = salesService.sendMessage(mobile, smsContent);
      JSONObject resultObject = JSON.parseObject(sendResult);
      if (resultObject.getIntValue("error") == 0) {
        return Message.success("");
      } else {
        return Message.error(resultObject.getString("content"));
      }
    }
  }

  @GetMapping("/sendFindPwdSms")
  public Message sendFindPwdSms(String mobile, String token) {
    int randomCode = StringUtil.getRangeRandomCode(100000, 999999);
    EhcacheHelper.put("randomCodeCache", token, randomCode);
    String smsContent = "【美素版权】找回密码验证码" + randomCode;
    String sendResult = salesService.sendMessage(mobile, smsContent);
    logger.info(smsContent);
    JSONObject resultObject = JSON.parseObject(sendResult);
    if (resultObject.getIntValue("error") == 0) {
      return Message.success("");
    } else {
      return Message.error(resultObject.getString("content"));
    }
  }

  @PostMapping("verifySmsCode")
  public Message verifySmsCode(String token, String randomCode) {
    Object randomCodeCache = EhcacheHelper.get("randomCodeCache", token);
    if (!randomCode.equals(randomCodeCache.toString())) {
      return Message.error("验证码错误");
    } else {
      return Message.success(null);
    }
  }

  @PostMapping("resetPassword")
  public Message resetPassword(String mobile, String password) {
    List<Users> users = usersRepo.findByUserNameIs(mobile);
    if (!StringUtil.isEmpty(users)) {
      Users users1 = users.get(0);
      int salt = StringUtil.getRangeRandomCode(1000, 9999);
      users1.setSalt(String.valueOf(salt));
      CustomPasswordEncode passwordEncode = new CustomPasswordEncode();
      String encodePwd = passwordEncode.encodePassword(password, users1.getSalt());
      users1.setPassword(encodePwd);
      usersRepo.save(users);
    }
    return Message.success(null);
  }

  @PostMapping("/userRegister")
  public Message register(Users users, String ctoken, String verifyCode) {
    Object randomCodeCache = EhcacheHelper.get("randomCodeCache", ctoken);
    if (!verifyCode.equals(randomCodeCache.toString())) {
      return Message.error("验证码错误");
    }
    int salt = StringUtil.getRangeRandomCode(1000, 9999);
    users.setSalt(String.valueOf(salt));
    CustomPasswordEncode passwordEncode = new CustomPasswordEncode();
    String encodePwd = passwordEncode.encodePassword(users.getPassword(), users.getSalt());
    users.setPassword(encodePwd);
    usersRepo.save(users);
    return Message.success("注册成功");
  }

  @GetMapping("/findMobile")
  public Message findMobile(String mobile) {
    List<Users> users = usersRepo.findByUserNameIs(mobile);
    if (StringUtil.isEmpty(users)) {
      return Message.error("");
    } else {
      return Message.success(null);
    }
  }

  @PostMapping("saveBuinessInfo")
  public Message saveBuinessInfo(BusinessCooperationInfo businessCooperationInfo) {
    accountService.saveBusinessCooperation(businessCooperationInfo);
    return Message.success(null);
  }

  @GetMapping("getRandom")
  public Message getRandom() {
    return Message.success(StringUtil.getRangeRandomCode(100000, 999999));
  }

  /**
   * 判断用户是否是VIP
   */
  @GetMapping("isHuabanUser")
  public Boolean isHuabanUser() {
    return accountService.isHuabanUser(getUserId());
  }


}
